// 获取应用实例
const app = getApp()
import {
    getNewProject,
    getNewProjectWorker,
    newDayExportWorkerList,
    deleteWorker,
    getInsurancePdf,
    confirmInsure,
} from '../../../api/app.js'
import {
    getInsurePlan,
    getInsuranceEnterprise,
    determineMicroInsure,
    getCheckInsuranceExpiration
} from '../../api/insurance'
import {
    toast,
    confirm,
    openDocument,
    getLocation,
    shake
} from '../../../utils/util.js'
import user from '../../../utils/user.js'
import Socket from '../../../api/socket.js'

const toastHistory = []
let pageNum = 1,
    notPage = false,
    searchValue = ''

Page({
    data: {
        isInsure: false, // 如果没有核身用户进入项目则不可点击 反之可投保
        succeedNum:0,
        failNum:0,
        minute: '00', //秒转的时间,
        second: '00', // 秒转秒
        timer: null, // 定时器
        countdown: 0, // 倒计时时间（单位：秒）
        isRunning: false, // 是否正在倒计时
        isSubmitPopup: false,
        top: app.globalData.menuTop,
        workers: [],
        date: '',
        companyName: '',
        companyId: '',
        recipient: '',
        projectName: '',
        projectNum: '',
        leader: [],
        women: 0,
        isTipInsurance: false,
        tipTop: 0,
        men: 0,
        workerCount: 0,
        morePosition: 0,
        showMoreStatus: false,
        projectId: 0,
        showGodAddStatus: false,
        copyLinkStatus: false,
        copyLinkContent: '',
        isOld: false,
        clockStartTime: '',
        clockEndTime: '',
        clockAddress: '',
        staffUnderpay: 0,
        setStaffUnderpayStatus: false,
        dayNightFlag: 0,
        signInType: '',
        collect: [],
        isOpenWesure: false,
        wesureIsDelete: false,
        tipTop: 0,
        wesureState: 0, // 控制我要投保按钮 是否可以点击
        createUserId: '',
        already: [],
        pageNum: 1,
        hasNextPage: Boolean,
        isAgain: 0,
        insureCompanyType: '',
        isDeleteSeverCompany: 0,
        industryPlanId: '',
        leftSecond:0,
        failRepeatNum:0
    },
    onLoad(options) {
        user.waitLogin().then((user) => {
            console.log(user, 'addadd')
            // /api/v2/webSocket/' + options.id + '/' + user.userId
            this.setData({
                insureCompanyType: user.insureCompanyType,
                socket: new Socket('/api/v2/webSocket/' + options.id + '/' + user.userId, (message) => {
                    try {
                        const data = JSON.parse(message.data)
                        console.log('data', data)
                        switch (data.type) {
                            case 'add': // 人员加入
                                console.log(data, '人员加入了的信息')
                                for (const item in this.data.workers) { // 防止刷新后的重复加入
                                    if (data.data.id === item.id) {
                                        return
                                    }
                                }
                                data.data.userName = data.data.workerName
                                data.data.workerName = data.data.workerName + '（' + data.data.idCardNo.slice(-4) + '）'
                                data.data.showAll = false
                                data.data.key = data.data.id
                                data.data.policyStatus = '员工待确认'
                                this.data.workers.unshift(data.data)
                                this.setData({
                                    workers: this.data.workers,
                                    workerCount: this.data.workerCount + 1,
                                    men: this.data.men + (data.data.sex == '0' ? 1 : 0),
                                    women: this.data.women + (data.data.sex == '0' ? 0 : 1),
                                })
                                console.log(this.data.workers, '更新的数据')
                                break
                            case 'update-auth': // 核实信息更新
                                console.log(data, 'datadata核实信息更新')
                                this.data.workers.forEach((item, index) => {
                                    if (item.userId === data.data.userId) {
                                        this.data.workers[index].alreadyInsuredProjectId = data.data.alreadyInsuredProjectId
                                        this.data.workers[index].leftSecond = data.data.leftSecond
                                        this.data.workers[index].policyStatus = data.data.insuredStatusCn
                                        this.setData({
                                            workers: this.data.workers,
                                        })
                                        return
                                    }
                                })
                                this.setData({
                                    isInsure:false,
                                })
                                if (!this.data.isRunning) {
                                    this.setData({
                                        countdown: data.data.leftSecond
                                    })
                                    this.getCheckInsuranceExpiration()
                                }
                                break
                            case 'modify': // 状态更新
                                console.log(data, '状态更新')
                                this.data.workers.forEach((item, index) => {
                                    if (item.userId === data.data.userId) {
                                        this.setData({
                                            ['workers[' + index + '].policyStatus']: data.data.insuredStatusCn,
                                            ['workers[' + index + '].expiredTime']: data.data.expiredTime,
                                            ['workers[' + index + '].key']: this.data.workers[index].id + '' + data.data.insuredStatusCn,
                                        })
                                        return
                                    }
                                })
                                break
                            case 'delete': // 有员工被删除
                                this.data.workers.forEach((item, index) => {
                                    if (item.userId === data.data.userId) {
                                        this.data.workers.splice(index, 1)
                                        this.setData({
                                            workers: this.data.workers,
                                            workerCount: this.data.workerCount - 1,
                                            men: this.data.men - (data.data.sex == '0' ? 1 : 0),
                                            women: this.data.women - (data.data.sex == '0' ? 0 : 1),
                                        })
                                        return
                                    }
                                })
                                break
                            case 'update':
                                console.log('触发更新')
                                this.data.workers.forEach((item, index) => {
                                    if (item.id === data.data.id) {
                                        this.setData({
                                            ['workers[' + index + '].remark']: data.data.remark
                                        })
                                        return
                                    }
                                })
                                console.log(this.data.workers, 'workersworkers')
                                break
                            case 'exception':
                                if (toastHistory.indexOf(data.data.msg) === -1)
                                    app.alert(data.data.msg)
                                break
                            default:
                                console.log(data, '什么都不匹配')
                        }
                    } catch (e) {
                        // 非JSON请求
                        console.log(message.data)
                    }
                })
            })
            console.log(options, 'options')
            if (options.isAgain === 5) {
                let value = 0
                this.setData({
                    wesureState: value,
                    projectId: options.id,
                    isAgain: 5
                })
            } else {
                this.setData({
                    projectId: options.id,
                })
            }
        })
    },
    onShow() {
        user.waitLogin().then(() => {
            this.setData({
                workers: [],
                pageNum: 1,
            })
            // if(this.data.isAgain === 5){
            //     this.getProject(isAgain == 5)
            this.getProjectWorker(notPage = false)
            // }else{  
            this.getProject()
            // this.getProjectWorker(notPage = false)
            // }

        })
    },
    onUnload() {
        pageNum = 1
        notPage = false
        searchValue = ''
        this.data.socket.close()
        this.closeToggle()
        // this.getProjectWorker()
    },
    getProject(isAgain) {
        getNewProject({
            id: this.data.projectId
        }).then((res) => {
            // 判断是否为当天之前的项目
            const isOld = new Date(res.createTime).getTime() < new Date(new Date().toLocaleDateString()).getTime()
            console.log(res, '哈哈哈哈哈')
            this.setData({
                date: res.date,
                companyName: res.serveCompanyName,
                companyId: res.serveCompanyId,
                industryPlanId: res.industryPlanId,
                projectName: res.projectName,
                projectNum: res.projectNum,
                recipient: res.recipient,
                clockStartTime: res.signTimeStart,
                clockEndTime: res.signTimeEnd,
                clockAddress: res.signPlace,
                staffUnderpay: res.staffUnderpay,
                setStaffUnderpay: '',
                isOld,
                dayNightFlag: res.dayNightFlag,
                signInType: res.signInType,
                isOpenWesure: res.isOpenWesure,
                wesureIsDelete: res.serverCompanyIsDelete,
                wesureTypeName: res.wesureTypeName,
                wesureInfo: res.wesureInfo,
                expiredTimeGSC: res.expiredTimeGSC,
                wesureState: res.wesureState,
                createUserId: res.createUserId,
                isDeleteSeverCompany: res.isDeleteSeverCompany,
                leftSecond: res.wesureInfoDTO.leftSecond || 0
            }, () => {
                if (this.data.isAgain == 5) {
                    this.setData({
                        wesureState: 0
                    })
                }
                if (res.wesureInfoDTO.leftSecond > 0 && res.wesureState === 0) {
                    this.setData({
                        countdown: res.wesureInfoDTO.leftSecond
                    })
                    this.closeToggle()
                    this.handleToggle()
                }
            })
            if (res.isOpenWesure) {
                this.insuranceTime()
            }
        }).catch(rej=>{
            this.setData({
                wesureState: 9
            })
        })
    },

    // 获取员工列表
    getProjectWorker() {
        console.log(notPage, '调用拉吗')
        if (notPage) {
            return
        }
        getNewProjectWorker({
            projectId: this.data.projectId,
            searchText: searchValue,
            pageSize: 500,
            pageNum: this.data.pageNum,
        }).then(res => {
            if (this.data.workers.length == 0) {
                pageNum = 1
            }
            pageNum += 1
            if (!res.hasNextPage) {
                notPage = true
            }
            let already
            for (const i in res.list) {
                // + '（' + res.list[i].idCardNo.slice(-4) + '）'
                // res.list[i].workerName = res.list[i].workerName 
                res.list[i].showAll = false
                res.list[i].key = res.list[i].id + '处理中'
                already = res.list[i].alreadyInsuredProjectId
                if(res.list[i].policyStatus === '未投保'){
                    this.setData({
                        isInsure:false,
                    })
                }
                console.log(this.data.isInsure, '在调用列表时 看看这个状态')
            }
            // this.data.workers.push(...res.list)
            this.setData({
                workers: res.list,
                women: res.women,
                men: res.men,
                workerCount: res.count,
                already: already,
                pageNum: pageNum
            })
        })
    },

    getPeople() {
        //   if(!this.data.hasNextPage){
        this.getProjectWorker()
        //   }
    },

    insuranceTime() {
        // todo: 需要性能优化时，将需要修改的所有数据放入一个数组中，实现一次setData修改整体界面
        setInterval(() => {
            this.data.workers.forEach((item, index) => {
                if (item.countDown === 0) {
                    this.data.workers[index].policyStatus = this.data.workers[index].policyStatus || '处理中'
                    this.data.workers[index].key = this.data.workers[index].id + '处理中'
                    this.data.workers[index].countDown = false
                    confirmInsure({
                        authRecordId: this.data.workers[index].payrollCardRecordId
                    })
                }
                if (item.countDown) {
                    this.data.workers[index].countDown = item.countDown - 1
                }
            })
            this.setData({
                workers: this.data.workers
            })
        }, 1000)
    },
    // 搜索员工
    searchWorker(event) {
        notPage = false
        searchValue = event.detail.value
        shake(()=>{
            this.setData({
                workers: [],
                pageNum: 1,
            })
            this.getProjectWorker()
        })
    },
    
    // 打电话
    call(event) {
        wx.makePhoneCall({
            phoneNumber: event.detail
        })
    },
    // 标记大神
    markGod(event) {
        console.log(this.data.workers)
        this.setData({
            showGodAddStatus: true,
            godBasicMsg: this.data.workers[event.detail]
        })
    },
    // 删除员工
    deleteWorker(event) {
        app.confirm('是否删除该员工?').then(() => {
            console.log(event, 'eventevent111111111')
            deleteWorker({
                id: this.data.workers[event.currentTarget.dataset.index].id
            }).then(() => {
                app.toast('删除成功!', 'success')
                setTimeout(() => {
                    pageNum = 1
                    notPage = false
                    this.setData({
                        workers: [],
                        pageNum: pageNum
                    })
                    this.getProjectWorker()
                }, 1000)
            })
        })
    },

    onExamine(event) {
        let id = event.currentTarget.dataset.id
        wx.navigateTo({
            url: '/packageMicroInsurance/pages/insurance-insure-detail/insurance-insure-detail?id=' + id + '&showmore=' + true,
        })
    },
    // 导出名单
    exportWorkerList() {
        newDayExportWorkerList({
            projectId: this.data.projectId
        }).then(res => {
            console.log(res, '导出名单导出名单')
            const url = app.globalData.baseUrl + '/common/download?fileName=' + res +
                '&delete=false'
            console.log(url)
            if (wx.canIUse('openDocument')) {
                const projectName = this.data.projectName.replace(/\//g, '.') + '.xlsx'
                openDocument(url, projectName).then(() => {}, () => {
                    this.setData({
                        copyLinkStatus: true,
                        copyLinkContent: url
                    })
                })
            } else {
                this.setData({
                    copyLinkStatus: true,
                    copyLinkContent: url
                })
            }
        })
    },

    // 前往用户个人信息界面
    onGoWorker(event) {
        console.log(event.currentTarget.dataset.islogout, 'events')
        if (event.currentTarget.dataset.islogout !== 0) {
            toast('该用户已注销')
            return
        }
        const workerId = event.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/worker/index/index?id=' + workerId
        })
    },
    // 下载保单pdf
    previewInsurance(event) {
        console.log(this.data.workers, 'this.data.workers')
        console.log(this.data.workers[event.detail])
        if(this.data.workers[event.detail].alreadyInsuredProjectId){
            wx.redirectTo({
                url: '/packageMicroInsurance/pages/insurance-insure-detail/insurance-insure-detail?id=' + this.data.workers[event.detail].alreadyInsuredProjectId
            })
            return
        }
        getInsurancePdf({
            id: this.data.workers[event.detail].wesureRecordId
        }).then(pdf => {
            console.log(pdf)
            if (wx.canIUse('openDocument')) {
                console.log('可以使用吗')
                const projectName = this.data.workers[event.detail].workerName + this.data.date + '保单.pdf'
                openDocument(pdf, projectName).then(() => {}, (rej) => {
                    console.log(rej, 'rejrej1返回错误')
                    this.setData({
                        copyLinkStatus: true,
                        copyLinkContent: pdf
                    })
                })
            } else {
                console.log('可以使用吗false')
                this.setData({
                    copyLinkStatus: true,
                    copyLinkContent: pdf
                })
            }
        })
    },
    // 开启确认投保弹窗
    onIsSubmitPopup(){
        // 先不限制 后面上线后放开
        // if (this.data.createUserId !== user.userId) {
        //     app.toast('仅创建者可操作')
        //     return
        // }
        // if (this.data.workers.length === 0) {
        //     app.toast('暂无人员，不可投保')
        //     return
        // }
        let succeedNum = 0
        let failNum = 0
        let failRepeatNum = 0
        this.data.workers.forEach(item=>{
            if(/(未投保|已失效|投保失败|取消|过期)/.test(item.policyStatus)){
                succeedNum += 1
            }else if(item.alreadyInsuredProjectId){
                failRepeatNum += 1
            }else if(!item.policyStatus){
                failNum += 1
            }
        })
        this.setData({
            isSubmitPopup: true,
            succeedNum,
            failNum,
            failRepeatNum
        })
    },
    // 关闭确认投保弹窗
    onCloseSubmitPopup(){
        
        this.setData({
            isSubmitPopup:false
        })
    },
    async onConfirmInsure(event) {
        const enterpriseList = await getInsuranceEnterprise({
            insureCompanyType: 'insure_type_tyrb'
        })
        const enterpriseIndex = await enterpriseList.filter(item => item.id === this.data.companyId)
        console.log(enterpriseIndex, 'enterpriseIndex')
        if (enterpriseIndex.length === 0) {
            app.toast('当前派遣单位状态异常,请检查')
            return
        } else {
            const programmeList = await getInsurePlan({
                serveCompanyId: this.data.companyId
            })
            const programmeIndex = programmeList.filter(item => item.id === this.data.industryPlanId)
            console.log(programmeIndex, 'programmeIndex')
            // wesurePlanName this.data.wesureTypeName
            if (programmeIndex.length === 0) {
                app.toast('方案不存在，请重新发起保单')
                return
            } else if (programmeIndex[0].industryPlanName !== this.data.wesureTypeName) {
                app.toast('当前方案已被修改，请重新发起保单')
                return
            }
        }
        if (this.data.isDeleteSeverCompany) {
            app.toast('派遣企业已被删除')
            return
        }
        if (this.data.createUserId !== user.userId) {
            app.toast('仅创建者可操作')
            return
        }
        // 前后端的约定 已投保的人员在上面 所以啊需要判断第一个就可以了
        // if (this.data.workers[0].alreadyInsuredProjectId !== null) {
        //     app.toast('人员列表中存在已投保人员，请删除已投保人员后提交')
        //     return
        // }
        if (this.data.workers.length === 0) {
            app.toast('暂无人员，不可投保')
            return
        }
        // app.confirm('确认投保吗？').then(async () => {
            const result = await determineMicroInsure({
                projectId: this.data.projectId
            })
            console.log(result, '确认投保返回的结果')
            // if (result?.code && result?.code === 2) {
            //     app.toast('已有人三小时内已投保')
            //     setTimeout(() => {
            //         this.onShow()
            //     }, 1500)
            //     return
            // }
            if(result.successList > 0){
                this.setData({
                    isInsure:true
                })
            }else{
                this.setData({
                    isInsure:false
                })
            }
            pageNum = 1
            notPage = false
            this.setData({
                workers: [],
            })
            await this.getProject()
            await this.getProjectWorker()
            
            // 关闭弹窗
            this.onCloseSubmitPopup()
            // 关闭定时器
            this.closeToggle()
            app.toast('投保成功')
        // })
    },
    tipInsurance(event) {
        console.log(event)
        console.log(event.currentTarget.top)
        this.setData({
            isTipInsurance: true,
            tipTop: event.currentTarget.offsetTop + 20,
            tipLeft: 110
        })
    },
    cancelTipInsurance() {
        // console.log('点击啦')
        if (this.data.isTipInsurance) {
            this.setData({
                isTipInsurance: false
            })
        }
    },
    // 海报邀请员工界面
    goInvitationPoster() {
        wx.navigateTo({
            url: '/packageMicroInsurance/pages/invitation-poster/invitation-poster?projectName=' + this.data.projectName + '&projectId=' + this.data.projectId + '&poster=4' + '&type=6'
        })
    },
    // 保险邀请员工需要前置定位
    onInsurancePost() {
        getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
        }).then(res => {
            this.setData({
                invitationStatus: false
            })
            wx.navigateTo({
                url: '/packageMicroInsurance/pages/invitation-poster/invitation-poster?projectName=' + this.data.projectName + '&projectId=' + this.data.projectId + '&coord=' + (res.longitude + ',' + res.latitude)
            })
        })
        // /packageInsurance/pages/insurance-poster/insurance-poster
    },

    // 开始/停止倒计时
    handleToggle() {
        const timer = setInterval(() => {
            let {
                countdown
            } = this.data;
            if (countdown === 1 || countdown < 1) { // 时间到了，清除定时器
                clearInterval(this.data.timer);
                this.getProject()
                this.getProjectWorker()
                this.setData({
                    isInsure: true
                })
                return
                this.setData({
                    isRunning: false
                });
            } else {
                --countdown; // 倒计时减一
                this.setData({
                    minute: parseInt(countdown / 60), //秒转的时间,
                    second: parseInt(countdown / 60) == 0 && countdown % 60 == '01' ? 0 : countdown % 60 , // 秒转秒
                    countdown
                });
            }
        }, 1000);
        this.setData({
            timer,
            isRunning: true
        });
    },
    // 清除倒计时
    closeToggle() {
        clearInterval(this.data.timer); // 清除定时器
        this.setData({
            minute: '00', //秒转的时间,
            second: '00', // 秒转秒
            isRunning: false
        }); // 更新状态
    },
    // 获取岗位自动提交时间
    async getCheckInsuranceExpiration(){
        const result = await getCheckInsuranceExpiration({
            id:this.data.projectId
        })
        console.log('result时间检测',result)
        if (result.leftSecond > 0) {
            this.setData({
                countdown: result.leftSecond,
                leftSecond: result.leftSecond
            })
            this.handleToggle()
        }
    },
    showMore(event) {
        console.log(event, 'eventevent')
        const index = event.currentTarget.dataset.index
        const list = []
        if (this.data.wesureState == 1 || this.data.wesureState == 2) {
            list.push({
                text: '查看保单',
                key: index,
                icon: '/assets/img/preview.png',
                bind: 'preview'
            })
        }
        // if (event.currentTarget.dataset.phone)
        //     list.push({
        //         text: '电话',
        //         key: event.currentTarget.dataset.phone,
        //         icon: '/assets/img/call.png',
        //         bind: 'call'

        //     })
        // list.push({
        //     text: '删除',
        //     key: index,
        //     icon: '/assets/img/delete.png',
        //     bind: 'delete'
        // })
        this.setData({
            'moreList': list
        })
        this.setData({
            morePosition: event.touches[0].clientY + 6,
            showMoreStatus: true
        })
    },
    // 隐藏显示更多
    hideMore() {
        this.setData({
            showMoreStatus: false
        })
    },
    // 关闭
    hideCopyLink() {
        this.setData({
            copyLinkStatus: false
        })
    },
    // 复制pdf下载链接
    copyWorkerListLink() {
        wx.setClipboardData({
            data: this.data.copyLinkContent,
            success:()=> {
                this.setData({
                    copyLinkStatus: false
                })
            }
        })
    },
})